package com.weather.androidweather;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.view.WindowManager;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.cardview.widget.CardView;

import com.weather.androidweather.databinding.ActivityMainBinding;
import com.weather.androidweather.model.DayForecast;
import com.weather.androidweather.model.WeatherData;
import com.weather.androidweather.service.WeatherService;
import com.weather.androidweather.util.WeatherIconUtil;
import com.weather.androidweather.service.WeatherAlertService;
import com.weather.androidweather.util.LocationHelper;
import com.weather.androidweather.util.ThreadPoolManager;

import java.util.ArrayList;
import java.util.List;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.components.Legend;
import android.graphics.Color;
import com.github.mikephil.charting.formatter.ValueFormatter;
import android.os.Build;
import com.github.mikephil.charting.animation.Easing;
import com.weather.androidweather.view.CustomMarkerView;
import android.widget.SearchView;
import android.widget.ListView;
import com.weather.androidweather.adapter.CityListAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import com.weather.androidweather.model.CityData;
import android.widget.ArrayAdapter;

public class MainActivity extends AppCompatActivity {
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1001;
    private static final int NOTIFICATION_PERMISSION_REQUEST_CODE = 1002;
    private static final String API_KEY = "a8d517e4476022233d4d25938edd8eab";
    private static final String TAG = "MainActivity";

    private ActivityMainBinding binding;
    private TextView windText;
    private TextView cityNameText;
    private TextView temperatureText;
    private TextView humidityText;
    private TextView weatherConditionText;
    private TextView todayTemperatureText;
    private TextView tomorrowTemperatureText;
    private SwipeRefreshLayout swipeRefresh;
    private ImageView backgroundImage;
    private LineChart temperatureChart;
    private WeatherAlertService alertService;
    private LocationHelper locationHelper;
    private WeatherService weatherService;
    private String currentCity = "北京"; // 默认城市

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        Log.d(TAG, "MainActivity onCreate");
        
        // 初始化视图
        initViews();
        Log.d(TAG, "视图初始化完成");
        
        // 初始化服务
        initServices();
        Log.d(TAG, "服务初始化完成");
        
        // 初始化定位
        locationHelper = new LocationHelper(this);
        Log.d(TAG, "定位服务初始化完成");
        
        // 检查定位权限
        checkLocationPermission();
    }

    private void initViews() {
        windText = binding.windText;
        cityNameText = binding.cityNameText;
        temperatureText = binding.temperatureText;
        humidityText = binding.humidityText;
        weatherConditionText = binding.weatherConditionText;
        todayTemperatureText = binding.todayTemperatureText;
        tomorrowTemperatureText = binding.tomorrowTemperatureText;
        swipeRefresh = binding.swipeRefresh;
        backgroundImage = binding.backgroundImage;
        temperatureChart = binding.temperatureChart;
        
        // 添加城市选择按钮
        ImageButton changeCityButton = binding.changeCityButton;
        changeCityButton.setOnClickListener(v -> showCityInputDialog());
        
        // 添加5天预报卡片点击事件
        binding.forecast7DaysCard.setOnClickListener(v -> {
            if (weatherService.getCurrentWeatherData() != null && 
                !weatherService.getCurrentWeatherData().getForecasts().isEmpty()) {
                Intent intent = new Intent(MainActivity.this, ForecastDetailActivity.class);
                intent.putParcelableArrayListExtra("forecasts", 
                    new ArrayList<>(weatherService.getCurrentWeatherData().getForecasts()));
                startActivity(intent);
            }
        });
    }

    private void initServices() {
        weatherService = new WeatherService(this);
        alertService = new WeatherAlertService(this);
    }

    private void checkLocationPermission() {
        Log.d(TAG, "检查定位权限");
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
            ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            
            Log.d(TAG, "请求定位权限");
            ActivityCompat.requestPermissions(this,
                    new String[]{
                            Manifest.permission.ACCESS_FINE_LOCATION,
                            Manifest.permission.ACCESS_COARSE_LOCATION
                    },
                    LOCATION_PERMISSION_REQUEST_CODE);
        } else {
            Log.d(TAG, "已有定位权限，开始定位");
            startLocation();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
            boolean allGranted = true;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allGranted = false;
                    break;
                }
            }
            
            if (allGranted) {
                Log.d(TAG, "用户授予了定位权限");
                startLocation();
            } else {
                Log.w(TAG, "用户拒绝了定位权限");
                Toast.makeText(this, "需要定位权限才能获取当前位置", Toast.LENGTH_SHORT).show();
                // 使用默认城市
                getWeatherForCity("北京");
            }
        }
    }

    private void startLocation() {
        Log.d(TAG, "开始定位");
        locationHelper.startLocation(new LocationHelper.LocationCallback() {
            @Override
            public void onSuccess(String city) {
                Log.d(TAG, "定位成功，城市: " + city);
                // 更新UI显示城市名
                runOnUiThread(() -> {
                    cityNameText.setText(city);
                    // 获取该城市的天气信息
                    getWeatherForCity(city);
                });
            }

            @Override
            public void onFailed(String error) {
                Log.e(TAG, "定位失败: " + error);
                // 使用默认城市
                runOnUiThread(() -> {
                    Toast.makeText(MainActivity.this, "定位失败，使用默认城市", Toast.LENGTH_SHORT).show();
                    // 使用默认城市获取天气
                    getWeatherForCity("北京");
                });
            }
            
            @Override
            public void onPermissionDenied() {
                Log.e(TAG, "定位权限被拒绝");
                // 使用默认城市
                runOnUiThread(() -> {
                    Toast.makeText(MainActivity.this, "需要定位权限才能获取当前位置，使用默认城市", Toast.LENGTH_SHORT).show();
                    // 使用默认城市获取天气
                    getWeatherForCity("北京");
                });
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (locationHelper != null) {
            locationHelper.destroy();
        }
        // 关闭线程池
        ThreadPoolManager.getInstance().shutdown();
    }

    private void getWeatherForCity(String cityName) {
        if (cityName == null || cityName.isEmpty()) {
            Log.e(TAG, "城市名称为空");
            Toast.makeText(this, "城市名称不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        // 去掉城市名称中的"市"字
        String formattedCityName = cityName.replace("市", "");
        Log.d(TAG, "开始获取天气数据，城市：" + formattedCityName);
        
        // 显示加载状态
        runOnUiThread(() -> {
            if (swipeRefresh != null) {
                swipeRefresh.setRefreshing(true);
            }
            // 更新城市名称显示
            cityNameText.setText(cityName);
        });

        // 使用线程池异步获取天气数据
        ThreadPoolManager.getInstance().execute(() -> {
            weatherService.getWeatherByCity(formattedCityName, new WeatherService.WeatherCallback() {
                @Override
                public void onSuccess(final WeatherData weatherData) {
                    Log.d(TAG, "获取天气数据成功");
                    runOnUiThread(() -> {
                        if (weatherData != null) {
                            updateWeatherUI(weatherData);
                        } else {
                            Toast.makeText(MainActivity.this, "获取天气数据失败", Toast.LENGTH_SHORT).show();
                        }
                        if (swipeRefresh != null) {
                            swipeRefresh.setRefreshing(false);
                        }
                    });
                }

                @Override
                public void onError(final String message) {
                    Log.e(TAG, "获取天气数据失败：" + message);
                    runOnUiThread(() -> {
                        Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
                        if (swipeRefresh != null) {
                            swipeRefresh.setRefreshing(false);
                        }
                    });
                }
            });
        });
    }

    private void setupChart() {
        if (temperatureChart == null) return;
        
        // 基本配置
        temperatureChart.getDescription().setEnabled(false);
        temperatureChart.setTouchEnabled(true);
        temperatureChart.setDragEnabled(true);
        temperatureChart.setScaleEnabled(true);
        temperatureChart.setPinchZoom(true);
        temperatureChart.setDrawGridBackground(false);
        temperatureChart.setBackgroundColor(Color.TRANSPARENT);
        temperatureChart.setNoDataText(getString(R.string.loading_weather_data));
        temperatureChart.setNoDataTextColor(Color.WHITE);
        // 增加上下边距，使图表更高
        temperatureChart.setExtraOffsets(16f, 80f, 16f, 80f);
        
        // X轴配置
        XAxis xAxis = temperatureChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setTextColor(Color.WHITE);
        xAxis.setTextSize(14f);
        xAxis.setGranularity(1f);
        xAxis.setLabelRotationAngle(0);
        xAxis.setYOffset(20f);
        xAxis.setAvoidFirstLastClipping(true);
        
        // Y轴配置
        YAxis leftAxis = temperatureChart.getAxisLeft();
        leftAxis.setDrawGridLines(true);
        leftAxis.setGridColor(getResources().getColor(R.color.chart_grid));
        leftAxis.setGridLineWidth(0.8f);
        leftAxis.setTextColor(Color.WHITE);
        leftAxis.setTextSize(14f);
        // 增加上下空间
        leftAxis.setSpaceTop(100f);
        leftAxis.setSpaceBottom(100f);
        leftAxis.setAxisLineColor(getResources().getColor(R.color.chart_axis));
        leftAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                return String.format("%.0f°", value);
            }
        });
        
        // 禁用右侧Y轴
        temperatureChart.getAxisRight().setEnabled(false);
        
        // 图例配置
        Legend legend = temperatureChart.getLegend();
        legend.setTextColor(Color.WHITE);
        legend.setTextSize(14f);
        legend.setForm(Legend.LegendForm.CIRCLE);
        legend.setFormSize(12f);
        legend.setXEntrySpace(20f);
        legend.setYEntrySpace(10f);
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
        
        // 添加标记线
        CustomMarkerView mv = new CustomMarkerView(this);
        mv.setChartView(temperatureChart);
        temperatureChart.setMarker(mv);
    }

    private void updateTemperatureChart(List<DayForecast> forecasts) {
        if (temperatureChart == null || forecasts == null || forecasts.isEmpty()) return;

        ArrayList<Entry> highTemps = new ArrayList<>();
        ArrayList<Entry> lowTemps = new ArrayList<>();
        ArrayList<String> xLabels = new ArrayList<>();
        
        float minTemp = Float.MAX_VALUE;
        float maxTemp = Float.MIN_VALUE;

        XAxis xAxis = temperatureChart.getXAxis();
        YAxis leftAxis = temperatureChart.getAxisLeft();

        for (int i = 0; i < forecasts.size(); i++) {
            DayForecast forecast = forecasts.get(i);
            float high = forecast.getMaxTemp();
            float low = forecast.getMinTemp();
            
            highTemps.add(new Entry(i, high));
            lowTemps.add(new Entry(i, low));
            
            // 格式化日期显示
            String dateLabel;
            if (i == 0) {
                dateLabel = getString(R.string.today);
            } else if (i == 1) {
                dateLabel = getString(R.string.tomorrow);
            } else {
                dateLabel = forecast.getFormattedDate().substring(5);
            }
            dateLabel += "\n" + forecast.getWeather();
            xLabels.add(dateLabel);
            
            minTemp = Math.min(minTemp, low);
            maxTemp = Math.max(maxTemp, high);
        }

        // 设置最高温度线
        LineDataSet highTempSet = new LineDataSet(highTemps, getString(R.string.high_temp));
        highTempSet.setColor(getResources().getColor(R.color.chart_high_temp));
        highTempSet.setCircleColor(getResources().getColor(R.color.chart_high_temp));
        highTempSet.setLineWidth(4f);
        highTempSet.setCircleRadius(10f);
        highTempSet.setDrawCircleHole(true);
        highTempSet.setCircleHoleRadius(5f);
        highTempSet.setValueTextSize(14f);
        highTempSet.setValueTextColor(Color.WHITE);
        highTempSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        highTempSet.setDrawFilled(true);
        highTempSet.setFillAlpha(50);
        highTempSet.setFillColor(getResources().getColor(R.color.chart_high_temp_fill));
        highTempSet.setDrawValues(true);
        
        // 设置最低温度线
        LineDataSet lowTempSet = new LineDataSet(lowTemps, getString(R.string.low_temp));
        lowTempSet.setColor(getResources().getColor(R.color.chart_low_temp));
        lowTempSet.setCircleColor(getResources().getColor(R.color.chart_low_temp));
        lowTempSet.setLineWidth(4f);
        lowTempSet.setCircleRadius(10f);
        lowTempSet.setDrawCircleHole(true);
        lowTempSet.setCircleHoleRadius(5f);
        lowTempSet.setValueTextSize(14f);
        lowTempSet.setValueTextColor(Color.WHITE);
        lowTempSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        lowTempSet.setDrawFilled(true);
        lowTempSet.setFillAlpha(50);
        lowTempSet.setFillColor(getResources().getColor(R.color.chart_low_temp_fill));
        lowTempSet.setDrawValues(true);

        LineData lineData = new LineData(highTempSet, lowTempSet);
        lineData.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                return String.format("%.0f°", value);
            }
        });
        temperatureChart.setData(lineData);
        
        // 设置Y轴范围
        float range = maxTemp - minTemp;
        float padding = range * 0.4f;  // 增加padding使图表更宽松
        leftAxis.setAxisMinimum(Math.max(0, minTemp - padding));
        leftAxis.setAxisMaximum(maxTemp + padding);
        
        // 设置X轴标签
        xAxis.setValueFormatter(new IndexAxisValueFormatter(xLabels));
        xAxis.setLabelCount(forecasts.size());
        
        // 添加动画效果
        temperatureChart.animateY(1500, Easing.EaseInOutQuad);
        temperatureChart.invalidate();
    }

    private void updateWeatherUI(WeatherData weatherData) {
        if (weatherData == null) {
            Log.e(TAG, "天气数据为空");
            return;
        }

        Log.d(TAG, "开始更新界面信息");
        
        // 更新城市名称
        if (weatherData.getCityName() != null) {
            cityNameText.setText(weatherData.getCityName());
            currentCity = weatherData.getCityName(); // 更新当前城市
        }
        
        // 更新当前温度
        if (weatherData.getTemperature() != 0) {
            temperatureText.setText(String.format("%.0f°", weatherData.getTemperature()));
        }
        
        // 更新天气状况
        if (weatherData.getWeatherCondition() != null) {
            weatherConditionText.setText(weatherData.getWeatherCondition());
        }
        
        // 更新湿度
        if (weatherData.getHumidity() != 0) {
            humidityText.setText(String.format("湿度: %d%%", weatherData.getHumidity()));
        }
        
        // 更新风力信息
        if (weatherData.getWindDirection() != null && weatherData.getWindPower() != null) {
            windText.setText(String.format("风力: %s %s级", 
                weatherData.getWindDirection(), weatherData.getWindPower()));
        }
        
        // 更新空气质量
        if (weatherData.getAqi() != null) {
            String aqiText = "空气质量: " + weatherData.getAqi();
            binding.aqiText.setText(aqiText);
            binding.aqiText.setVisibility(View.VISIBLE);
        } else {
            binding.aqiText.setVisibility(View.GONE);
        }
        
        // 更新今明两天温度
        if (weatherData.getForecasts() != null && !weatherData.getForecasts().isEmpty()) {
            DayForecast today = weatherData.getForecasts().get(0);
            todayTemperatureText.setText(String.format("%.0f°/%.0f°", 
                today.getMaxTemp(), today.getMinTemp()));
            
            if (weatherData.getForecasts().size() > 1) {
                DayForecast tomorrow = weatherData.getForecasts().get(1);
                tomorrowTemperatureText.setText(String.format("%.0f°/%.0f°", 
                    tomorrow.getMaxTemp(), tomorrow.getMinTemp()));
            }
        }
        
        // 更新时间
        if (weatherData.getUpdateTime() != null) {
            binding.updateTimeText.setText(weatherData.getUpdateTime());
        }
        
        // 根据天气状况更新背景
        if (weatherData.getWeatherCondition() != null) {
            updateBackgroundByWeather(weatherData.getWeatherCondition());
        }

        // 更新温度图表
        if (weatherData.getForecasts() != null && !weatherData.getForecasts().isEmpty()) {
            updateTemperatureChart(weatherData.getForecasts());
        }

        // 检查天气预警
        checkWeatherAlert(weatherData);

        // 停止刷新动画
        if (swipeRefresh != null) {
            swipeRefresh.setRefreshing(false);
        }
        
        Log.d(TAG, "界面信息更新完成");
    }

    private void checkWeatherAlert(WeatherData weatherData) {
        if (weatherData == null) return;

        String alertMessage = null;
        String weatherCondition = weatherData.getWeatherCondition();
        double temperature = weatherData.getTemperature();

        // 检查天气状况
        if (weatherCondition.contains("暴雨") || weatherCondition.contains("大暴雨")) {
            alertMessage = "暴雨预警：请注意防范强降雨可能带来的灾害";
        } else if (weatherCondition.contains("大雨")) {
            alertMessage = "大雨预警：请注意防范强降雨";
        } else if (weatherCondition.contains("中雨")) {
            alertMessage = "雨天提示：请携带雨具，注意出行安全";
        } else if (weatherCondition.contains("小雨") || weatherCondition.contains("阵雨")) {
            alertMessage = "雨天提示：请携带雨具";
        } else if (weatherCondition.contains("大雪") || weatherCondition.contains("暴雪")) {
            alertMessage = "暴雪预警：请注意防范积雪和道路结冰";
        } else if (weatherCondition.contains("台风")) {
            alertMessage = "台风预警：请注意防范大风和强降雨";
        } else if (weatherCondition.contains("雷电")) {
            alertMessage = "雷电预警：请注意防范雷击风险";
        } else if (weatherCondition.contains("冰雹")) {
            alertMessage = "冰雹预警：请注意防范冰雹灾害";
        } else if (weatherCondition.contains("沙尘暴")) {
            alertMessage = "沙尘暴预警：请注意防范沙尘天气";
        } else if (weatherCondition.contains("雾")) {
            alertMessage = "大雾预警：请注意交通安全";
        }

        // 检查温度
        if (temperature >= 35) {
            alertMessage = "高温预警：请注意防暑降温";
        } else if (temperature <= -10) {
            alertMessage = "低温预警：请注意防寒保暖";
        }

        // 显示预警弹窗
        if (alertMessage != null) {
            new AlertDialog.Builder(this)
                .setTitle("天气预警")
                .setMessage(alertMessage)
                .setPositiveButton("确定", null)
                .setCancelable(false)
                .show();
            
            // 显示通知
            alertService.checkWeatherAlert(weatherData);
        }
    }

    private void updateBackgroundByWeather(String weather) {
        if (weather == null || weather.isEmpty()) return;

        int backgroundResId;
        
        // 根据天气类型设置对应的背景
        if (weather.contains("雪")) {
            backgroundResId = R.drawable.bg_weather_snowy;
        } else if (weather.contains("雨")) {
            backgroundResId = R.drawable.bg_weather_rainy;
        } else if (weather.contains("阴") || weather.contains("云")) {
            backgroundResId = R.drawable.bg_weather_cloudy;
        } else {
            // 默认晴天背景
            backgroundResId = R.drawable.bg_weather_sunny;
        }

        // 使用渐变动画切换背景
        final ImageView backgroundView = binding.backgroundImage;
        if (backgroundView != null) {
            // 创建渐变动画
            ObjectAnimator fadeOut = ObjectAnimator.ofFloat(backgroundView, "alpha", 1f, 0.3f);
            fadeOut.setDuration(500);
            ObjectAnimator fadeIn = ObjectAnimator.ofFloat(backgroundView, "alpha", 0.3f, 1f);
            fadeIn.setDuration(500);

            fadeOut.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    // 在淡出动画结束时更换背景图片
                    backgroundView.setImageResource(backgroundResId);
                    // 开始淡入动画
                    fadeIn.start();
                }
            });

            // 开始淡出动画
            fadeOut.start();
        }
    }

    private void refreshWeatherData() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            startLocation();
        } else {
            swipeRefresh.setRefreshing(false);
            Toast.makeText(this, R.string.refresh_permission_required, Toast.LENGTH_SHORT).show();
        }
    }

    private void showCityInputDialog() {
        try {
            // 检查文件是否存在
            String[] files = getAssets().list("");
            boolean fileExists = false;
            for (String file : files) {
                if (file.equals("cities.json")) {
                    fileExists = true;
                    break;
                }
            }

            if (!fileExists) {
                Log.e(TAG, "城市数据文件不存在");
                Toast.makeText(this, "城市数据文件不存在", Toast.LENGTH_SHORT).show();
                return;
            }

            // 读取城市数据
            InputStream is = getAssets().open("cities.json");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            String json = new String(buffer, StandardCharsets.UTF_8);

            // 解析JSON数据
            Gson gson = new Gson();
            Type type = new TypeToken<CityData>() {}.getType();
            CityData cityData = gson.fromJson(json, type);

            if (cityData == null || cityData.getProvinces() == null || cityData.getProvinces().isEmpty()) {
                Log.e(TAG, "城市数据解析失败");
                Toast.makeText(this, "城市数据解析失败", Toast.LENGTH_SHORT).show();
                return;
            }

            // 创建对话框
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(R.string.input_city_title);

            // 加载城市列表布局
            View dialogView = getLayoutInflater().inflate(R.layout.dialog_city_list, null);
            builder.setView(dialogView);

            // 初始化视图
            ListView provinceListView = dialogView.findViewById(R.id.provinceListView);
            ListView cityListView = dialogView.findViewById(R.id.cityListView);
            SearchView searchView = dialogView.findViewById(R.id.searchView);

            // 设置省份适配器
            List<String> provinceNames = new ArrayList<>();
            for (CityData.Province province : cityData.getProvinces()) {
                provinceNames.add(province.getName());
            }
            ArrayAdapter<String> provinceAdapter = new ArrayAdapter<>(this,
                    android.R.layout.simple_list_item_1, provinceNames);
            provinceListView.setAdapter(provinceAdapter);
            // 设置省份列表为单选模式
            provinceListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

            // 收集所有城市
            List<String> allCities = new ArrayList<>();
            for (CityData.Province province : cityData.getProvinces()) {
                allCities.addAll(province.getCities());
            }

            // 设置城市适配器
            CityListAdapter cityAdapter = new CityListAdapter(this, allCities);
            cityListView.setAdapter(cityAdapter);

            // 设置省份选择监听
            provinceListView.setOnItemClickListener((parent, view, position, id) -> {
                // 设置选中状态
                provinceListView.setItemChecked(position, true);
                String selectedProvince = provinceNames.get(position);
                for (CityData.Province province : cityData.getProvinces()) {
                    if (province.getName().equals(selectedProvince)) {
                        cityAdapter.updateCities(province.getCities());
                        break;
                    }
                }
            });

            // 设置搜索功能
            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    return false;
                }

                @Override
                public boolean onQueryTextChange(String newText) {
                    if (newText == null || newText.isEmpty()) {
                        // 如果搜索框为空，显示当前选中省份的城市
                        int selectedPosition = provinceListView.getCheckedItemPosition();
                        if (selectedPosition >= 0 && selectedPosition < provinceNames.size()) {
                            String selectedProvince = provinceNames.get(selectedPosition);
                            for (CityData.Province province : cityData.getProvinces()) {
                                if (province.getName().equals(selectedProvince)) {
                                    cityAdapter.updateCities(province.getCities());
                                    break;
                                }
                            }
                        } else if (!provinceNames.isEmpty()) {
                            // 如果没有选中的省份，默认显示第一个省份的城市
                            String firstProvince = provinceNames.get(0);
                            for (CityData.Province province : cityData.getProvinces()) {
                                if (province.getName().equals(firstProvince)) {
                                    cityAdapter.updateCities(province.getCities());
                                    break;
                                }
                            }
                        }
                    } else {
                        // 否则搜索所有城市
                        List<String> allCities = new ArrayList<>();
                        for (CityData.Province province : cityData.getProvinces()) {
                            allCities.addAll(province.getCities());
                        }
                        cityAdapter.updateCities(allCities);
                        cityAdapter.filter(newText);
                    }
                    return true;
                }
            });

            // 创建对话框
            final AlertDialog dialog = builder.create();

            // 设置城市选择监听
            cityListView.setOnItemClickListener((parent, view, position, id) -> {
                String selectedCity = cityAdapter.getItem(position);
                if (selectedCity != null && !selectedCity.isEmpty()) {
                    currentCity = selectedCity; // 更新当前城市
                    cityNameText.setText(selectedCity);
                    dialog.dismiss();
                    // 立即获取新城市的天气数据
                    getWeatherForCity(selectedCity);
                }
            });

            dialog.show();

            // 默认选择第一个省份
            if (!provinceNames.isEmpty()) {
                provinceListView.setItemChecked(0, true);
                String firstProvince = provinceNames.get(0);
                for (CityData.Province province : cityData.getProvinces()) {
                    if (province.getName().equals(firstProvince)) {
                        cityAdapter.updateCities(province.getCities());
                        break;
                    }
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "加载城市数据失败: " + e.getMessage());
            Toast.makeText(this, "加载城市数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "处理城市数据时发生错误: " + e.getMessage());
            Toast.makeText(this, "处理城市数据时发生错误", Toast.LENGTH_SHORT).show();
        }
    }

    private void fetchWeatherData(String cityName) {
        getWeatherForCity(cityName);
    }

    private void updateCityName(String cityName) {
        if (cityNameText != null) {
            cityNameText.setText(cityName);
        }
    }
}